from re import S
import re
from typing import Dict
from common.enum.stock_category_enum import StockCategoryEnum
from dto.strategy_calculate_result import StrategyCalculateResult
from service.das.stock_assessment_das import RiskAssessmentService
from service.das.stock_assessment_item_das import RiskAssessmentItemService
from service.das.stock_monitor_das import StockDas
from service.das.test import JsonPlaceholderReplacer
from service.setting_service import DataDictionaryService
from service.stock_service import StockMainService
from service.stock_view_service import StockViewService
from service.strategy_query_service import StrategyViewQueryService
from views.common.translator import Translator
from views.template_page_view import BasePageTemplateView, FormItemDto, TableDataDto
from PyQt6.QtWidgets import (
    QHBoxLayout,
)


class HomeView(BasePageTemplateView):

    def __init__(self, parent=None):
        t = Translator()
        super().__init__("HomeView", parent=parent)

    def doInitAndUpdate(self):

        self.mainStockFinal = self.getMainStockRiskDate()
        self.viewService = StockViewService()
        self.stock_risk = self.viewService.query_stocks_by_category_and_sort(
            category=StockCategoryEnum.INDIVIDUAL, sort_by="risk_level", limit=5
        )
        self.stock_focus = self.viewService.query_stocks_by_category_and_sort(
            category=StockCategoryEnum.INDIVIDUAL, sort_by="focus_level", limit=5
        )

        levelMain_HLayout = QHBoxLayout()
        self.addKeyValueFormTemplate(
            "大盘综合信息",
            self.getMainKeyMapTableRisk,
            self.getBaseParam,
            1,
            levelMain_HLayout,
        )
        self.addEchatTemplate(
            "大盘风险",
            "stock_risk",
            self.exchangeMainStockRisk,
            self.getBaseParam,
            1,
            levelMain_HLayout,
        )
        self.addOutLayout(levelMain_HLayout)

        self.addTableTemplate(
            "大盘风险报表", self.tableMainStockRisk, self.getBaseParam, 1
        )

        # 水平视图 ： Chat 默认以水平试图分为左右两个部分
        level1_HLayout = QHBoxLayout()
        # 再返回一个当前持股信息 Table
        self.addTableTemplate(
            "风险股",
            self.get_risk_level_table_info,
            self.getBaseParam,
            1,
            level1_HLayout,
        )

        self.addTableTemplate(
            "关注股",
            self.get_focus_level_table_info,
            self.getBaseParam,
            1,
            level1_HLayout,
        )
        self.addOutLayout(level1_HLayout)

        # 先返回一个当前持股信息 Echat
        level2_HLayout = QHBoxLayout()
        self.addEchatTemplate(
            "板块得分",
            "stock_recommend",
            self.exchangeRecommendData,
            self.getBaseParam,
            1,
            level2_HLayout,
        )

        self.addOutLayout(level2_HLayout)

        # 再返回一个当前持股信息 Table
        # self.addTableTemplate(
        #     "当前持股", self.getStockTableInfo, self.getBaseParam, 1, level1_HLayout
        # )

        # 添加外部组件
        # self.addOutLayout(level1_HLayout)

        # # 再返回一个当前持股信息 Table
        # self.addTableTemplate(
        #     "当前持股", self.getStockTableInfo, self.getBaseParam, 1
        # )

    # 用于返回当前的报表数据
    def exhcangeStockChatInfo(self, jsonData: str, params: Dict[str, str]) -> str:
        AntLogger.info(f"exhcangeStockChatInfo 传入查询的对象信息{params}")
        replacer = JsonPlaceholderReplacer(jsonData)
        return replacer.get_modified_json()

    # 用于标记当前的查询对象
    def getBaseParam(self) -> Dict[str, str]:
        return {"stockCode": "100001"}

    # 用于返回当前的报表数据
    def getStockTableInfo(self, params: Dict[str, str]) -> str:
        AntLogger.info(f"getStockTableInfo 传入查询的对象信息{params}")
        return TableDataDto(
            table_header=[
                "股票代码",
                "股票名称",
                "股票当前价",
                "当前盈亏比例",
                "当前风险等级",
            ],
            table_data=[
                ["600519", "贵州茅台", "1800.00", "+5.32%", "低风险"],
                ["000858", "五粮液", "120.00", "-2.15%", "中风险"],
                ["002304", "洋河股份", "95.50", "+1.25%", "高风险"],
            ],
            table_item_fun=[{"查看详情": self.showTableDatail}],
        )

    def exchangeRecommendData(self, jsonData: str, params: Dict[str, str]) -> str:
        source_data = [
            {
                "value": 99,
                "name": "半导体",
                "path": "10001",
                "children": [
                    {"value": 33, "name": "半导体1", "path": "Accounts/Access"},
                    {"value": 2, "name": "半导体2", "path": "Accounts/Authentication"},
                    {"value": 80, "name": "半导体3", "path": "Accounts/Notification"},
                ],
            },
            {
                "value": 15,
                "name": "金融证券",
                "path": "Accounts",
                "children": [
                    {"value": 76, "name": "国盛金控", "path": "Accounts/Access"},
                    {
                        "value": 92,
                        "name": "东方财富",
                        "path": "Accounts/Authentication",
                    },
                ],
            },
        ]
        replacer = JsonPlaceholderReplacer(jsonData)
        replacer.replace_placeholder("__STOCK_DATA__", source_data)
        return replacer.get_modified_json()

    def getMainKeyMapTableRisk(self, params: Dict[str, str]) -> str:
        """大盘 Risk Key-value 报表数据"""
        strategy_result = self.mainStockFinal
        stock_info = strategy_result.stock_info
        return {
            "股票代码": stock_info.stock_code if stock_info else "未知",
            "最新股价": strategy_result.latest_price,
            "计算总得分": strategy_result.total_score,
            "风险等级": strategy_result.risk_level,
            "关注等级": strategy_result.focus_level,
            "股票积分": stock_info.stock_final_point if stock_info else None,
            "关注等级（原始）": stock_info.stock_focus_level if stock_info else None,
            "风险等级（原始）": stock_info.stock_risk_level if stock_info else None,
            "更新时间": (
                stock_info.modified_date.strftime("%Y-%m-%d %H:%M:%S")
                if stock_info and stock_info.modified_date
                else None
            ),
        }

    def exchangeMainStockRisk(self, jsonData: str, params: Dict[str, str]) -> str:
        """大盘 Echat 分线报表数据"""
        strategy_names = []
        node_points = []
        for assessment in self.mainStockFinal.risk_assessments:
            strategy_names.append(assessment.config.strategy_name)
            node_points.append(assessment.node_point)

        replacer = JsonPlaceholderReplacer(jsonData)
        replacer.replace_placeholder("__CHAT_NAME__", "大盘风险表")
        replacer.replace_placeholder("__STRATEGY_NAME__", strategy_names)
        replacer.replace_placeholder("__NODE_POINT__", node_points)
        return replacer.get_modified_json()

    def tableMainStockRisk(self, params: Dict[str, str]) -> str:
        try:
            # 定义表格头
            table_header = [
                "股票代码",
                "策略名称",
                "风险等级",
                "策略分组",
                "分析天数",
                "节点得分",
                "描述",
            ]

            # 填充表格数据
            strategy_result = self.mainStockFinal
            table_data = []
            for assessment in strategy_result.risk_assessments:
                row = [
                    assessment.stock_code,
                    assessment.config.strategy_name,
                    str(assessment.config.strategy_level),
                    "风险型" if assessment.config.strategy_group == 0 else "关注型",
                    str(assessment.config.analysis_day),
                    str(assessment.node_point),
                    assessment.description,
                ]
                table_data.append(row)

                # 定义操作按钮回调函数

            def example_callback(stock_code: str) -> str:
                return f"查看股票 {stock_code} 的详情"

            # 创建 TableDataDto 对象
            table_item_fun = [{"详情": example_callback}]
            return TableDataDto(
                table_header=table_header,
                table_data=table_data,
                table_item_fun=table_item_fun,
            )

        except Exception as e:
            AntLogger.info(f"转换时出错: {e}")
            # 返回一个空的 TableDataDto 对象
            return TableDataDto(table_header=[], table_data=[], table_item_fun=[])

    def exchangeMainStockDate(self, jsonData: str, params: Dict[str, str]) -> str:
        source_data = [
            {"value": 40, "name": "rose 1"},
            {"value": 38, "name": "rose 2"},
            {"value": 32, "name": "rose 3"},
            {"value": 30, "name": "rose 4"},
            {"value": 28, "name": "rose 5"},
            {"value": 26, "name": "rose 6"},
            {"value": 22, "name": "rose 7"},
            {"value": 18, "name": "rose 8"},
        ]
        replacer = JsonPlaceholderReplacer(jsonData)
        replacer.replace_placeholder("__STOCK_DATA__", source_data)
        return replacer.get_modified_json()

    def tableSingleStockFocus(self, params: Dict[str, str]) -> str:
        return self.viewService.exchange_stock_table_info(self.stock_focus)

    def tableSingleStockRisk(self, params: Dict[str, str]) -> str:
        return self.viewService.exchange_stock_table_info(self.stock_risk)

    def get_stock_table_info(self, sortBy: str) -> TableDataDto:
        """
        根据传入的参数查询股票数据，并返回格式化的报表数据。
        :param params: 查询参数字典
        :return: TableDataDto 对象
        """
        AntLogger.info(f"getStockTableInfo 传入查询的对象信息{sortBy}")

        stockService = StockMainService()

        # 获取排序后的股票数据
        stock_list = stockService.listSelfStock(sort_by=sortBy)

        # 格式化股票数据为表格形式
        table_data = []
        for stock in stock_list:
            # 格式化股票数据
            stock_code = stock.stock_code
            stock_name = stock.stock_name
            stock_current_price = (
                f"{stock.monitor_current_price:.2f}"
                if stock.monitor_current_price
                else "N/A"
            )
            monitor_income_ratio = (
                f"{stock.monitor_income_ratio:.2f}%"
                if stock.monitor_income_ratio is not None
                else "N/A"
            )
            stock_risk_level = stockService.get_risk_level_description(
                stock.stock_risk_level
            )

            table_data.append(
                [
                    stock_code,
                    stock_name,
                    stock_current_price,
                    monitor_income_ratio,
                    stock_risk_level,
                ]
            )

        # 返回表格数据
        return TableDataDto(
            table_header=[
                "股票代码",
                "股票名称",
                "股票当前价",
                "当前盈亏比例",
                "当前风险等级",
            ],
            table_data=table_data,
            table_item_fun=[{"查看详情": self.showTableDatail}],
        )

    def showTableDatail(self, stock_code: str) -> str:
        return f"当前操作者的对象信息: {stock_code}"

    def getMainStockRiskDate(self):
        stockList = StockDas().get_stocks_byCategory(category=StockCategoryEnum.UNIQUE)
        if stockList:
            stockCode = stockList[0]
            strategyService = StrategyViewQueryService()
            finalResult = strategyService.searchFinalResult(stockCode)
            return finalResult
        else:
            return StrategyCalculateResult()
